﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;
using TappUpsRefresh.Extras;
using System.Threading;
using ImmunityBuster_wp7_2;

namespace SlXnaApp3
{
    public partial class LevelSelector : PhoneApplicationPage
    {
        List<Score> scores = new List<Score>();
        LevelStore levelsDone = new LevelStore();
        Thread ScoreCalcThread;
        public LevelSelector()
        {
            for (int i = 0; i < 5; i++)
            {
                levelsDone.Store.Add(new Levels()
                {
                    Level = "Level " + i.ToString(),
                    LevelNo = i,
                    Data = "NULL"
                });
            }

            ScoreCalcThread = new Thread(() =>
            {
                lock (scores)
                    CalculateScore();
            });
            InitializeComponent();
        }

        private void CalculateScore()
        {
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            XmlSerializer xmls = new XmlSerializer(typeof(Score));
            String[] list = isf.GetFileNames("*.score");

            foreach (String str in list)
            {
                using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(str, System.IO.FileMode.Open, isf))
                {
                    try
                    {
                        Score temp = (Score)xmls.Deserialize(isfs);
                        scores.Add(temp);
                        isfs.Close();
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show("An internal Error occured! We are sorry but some of your scores may not get loaded");
                        //isf.DeleteFile(str);
                    }
                }
            }


        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void listBox1_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Levels l = ((Levels)listBox1.SelectedItem);
            var res = MessageBox.Show(l.Level.ToString() + " " + l.LevelNo.ToString() + "\n" + l.Data.ToString(), "Play?", MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                NavigationService.Navigate(new Uri("/Gamepage.xaml", UriKind.RelativeOrAbsolute));
                //(App.Current as App).level = l;
            }
        }

        private void listBox1_Loaded(object sender, RoutedEventArgs e)
        {
            listBox1.Items.Clear();
            var stream1 = App.GetResourceStream(new Uri("levelInfo.txt", UriKind.Relative));
            var stream = stream1.Stream;
            StreamReader reader = new StreamReader(stream);
            String[] data = reader.ReadToEnd().Split(Environment.NewLine.ToCharArray().First());
            //for (int i = 0; i < 5; i++)
            //    listBox1.Items.Add(new Levels
            //    {
            //        Level = "Level " + i.ToString(),
            //        LevelNo = i,
            //        Data = data[i].Trim('\n').ToString()
            //    });

            //foreach (Score score in scores)
            //{
            //    if (levelsDone.Contains(score.LevelNo))
            //    {
            //        if (score.score < ((score.LevelNo) * 3))
            //        {
            //            List<Levels> temp = new List<Levels>();
            //            temp.
            //        }
            //        else
            //        {
            //            foreach (int i in levelsDone)
            //                if (i < score.LevelNo)
            //                    levelsDone.Remove(i);
            //            levelsDone.Remove(score.LevelNo);
            //        }
            //    }
            //}

            //foreach (Levels a in (App.Current as App).levelsDone.Store)
            //{                
            //    levelsDone.Store.Remove(a);
            //}

            listBox1.Items.Add(new Levels
            {
                Level = "Level " + "0",
                LevelNo = 0,
                Data = data[0].Trim('\n').ToString()
            });

            try
            {
                foreach (Levels a in levelsDone.Store)
                {
                    levelsDone.Store.Add(new Levels()
                    {
                        Level = a.Level,
                        LevelNo = a.LevelNo,
                        Data = a.Data
                    });

                }

            }
            catch (Exception _e)
            { }

            //listBox1.SelectedItem = listBox1.Items.ElementAt(((App.Current as App).level.LevelNo));
        }

        private void Button_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Levels l = ((Levels)listBox1.SelectedItem);
            var res = MessageBox.Show(l.Level.ToString() + " " + l.LevelNo.ToString() + "\n" + l.Data.ToString(), "Play?", MessageBoxButton.OKCancel);
            if (res == MessageBoxResult.OK)
            {
                //(App.Current as App).level = l;
                NavigationService.Navigate(new Uri("/Gamepage.xaml", UriKind.RelativeOrAbsolute));
            }
        }
    }
}

public class Levels
{
    public String Level { get; set; }
    public int LevelNo { get; set; }
    public String Data { get; set; }


    public Levels()
    {
        LevelNo = 0;
        Level = " Level 0";
        Data = "Null";
    }


}